import requests
from flask import Flask, request, jsonify, render_template
import pymysql
from pymysql.cursors import DictCursor

from utils.printSelf import log_info


app = Flask(__name__)


# MySQL 配置
MYSQL_CONFIG = {
    'host': '10.32.15.46',
    'port': 11096,
    'user': 'root',
    'password': 'kqYMmrzfbz5Ppmt4',
    'database': 'autopaste',
    'cursorclass': DictCursor
}

# 假设的 DeepSeek API 配置（需替换为实际值）
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
DEEPSEEK_API_KEY = "sk-8913661ff655435ea30997b1eb6d2737"


# 存储会话数据（模拟 AI 优化过程）
sessions = {}

def get_db_connection():
    """获取 MySQL 数据库连接"""
    return pymysql.connect(**MYSQL_CONFIG)

def init_db():
    """初始化数据库表"""
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS commands (
                    session_id BIGINT PRIMARY KEY,
                    command TEXT
                )
            """)
        conn.commit()
        print("数据库表初始化完成（如果不存在）")
    except Exception as e:
        print(f"初始化数据库失败: {e}")
    finally:
        if 'conn' in locals():
            conn.close()

@app.route("/")
def index():
    """渲染前端页面"""
    return render_template("index.html")

@app.route("/generate", methods=["POST"])
def generate_initial_command():
    try:
        data = request.json
        text = data["text"]
        session_id = data["session_id"]

        log_info(text)

        # 构造符合 DeepSeek API 要求的 payload
        headers = {"Authorization": f"Bearer {DEEPSEEK_API_KEY}"}
        payload = {
            "model": "deepseek-coder",  # 替换为实际模型名称
            "messages": [{"role": "user", "content": f"根据文本生成命令：{text}"}],
            "max_tokens": 100,
            "temperature": 0.3
        }

        # 发送请求并记录详细日志
        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload)
        response.raise_for_status()
        result = response.json()

        # 提取生成的命令（根据实际API响应结构调整）
        initial_command = result["choices"][0]["message"]["content"]

        # 存储会话数据
        sessions[session_id] = {
            "text": text,
            "command": initial_command,
            "history": [f"初始命令: {initial_command}"]
        }

        return jsonify({"command": initial_command})

    except requests.exceptions.HTTPError as e:
        error_msg = f"API请求失败: {e.response.status_code} - {e.response.text}"
        return jsonify({"error": error_msg}), 502
    except KeyError as e:
        return jsonify({"error": f"响应数据解析失败: 缺少字段 {e}"}), 500
    except Exception as e:
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500

# @app.route("/generate", methods=["POST"])
# def generate_initial_command():
#     """生成初始命令"""
#     data = request.json
#     text = data["text"]
#     session_id = data["session_id"]
#
#     # 模拟 AI 生成命令（实际项目调用 DeepSeek API）
#     initial_command = f"# 根据文本生成的初始命令\n"
#
#     # 存储会话数据
#     sessions[session_id] = {
#         "text": text,
#         "command": initial_command,
#         "history": [f"初始命令: {initial_command}"]
#     }
#
#     return jsonify({"command": initial_command})

@app.route("/optimize", methods=["POST"])
def optimize_command():
    """根据反馈优化命令"""
    data = request.json
    feedback = data["feedback"]
    session_id = data["session_id"]

    if session_id not in sessions:
        return jsonify({"error": "会话不存在"}), 400

    current_command = sessions[session_id]["command"]
    history = sessions[session_id]["history"]

    # 模拟 AI 根据反馈优化命令（实际项目调用 DeepSeek API）
    if "sudo" in feedback.lower():
        new_command = current_command.replace("find", "sudo find")
    elif "权限" in feedback:
        new_command = current_command.replace("-delete", "-exec chmod 644 {} \; -delete")
    else:
        new_command = current_command + "\n# 根据反馈添加的注释"

    # 更新会话数据
    sessions[session_id]["command"] = new_command
    history.append(f'反馈: "{feedback}" → 优化后: {new_command}')
    sessions[session_id]["history"] = history

    return jsonify({"command": new_command})

@app.route("/save_to_mysql", methods=["POST"])
def save_to_mysql():
    """存入 MySQL"""
    data = request.json
    command = data["command"]
    session_id = data["session_id"]

    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            # 插入或更新命令
            sql = """
                INSERT INTO commands (session_id, command) 
                VALUES (%s, %s) 
                ON DUPLICATE KEY UPDATE command = %s
            """
            cursor.execute(sql, (session_id, command, command))
        conn.commit()
        return jsonify({"message": "命令已存入 MySQL 数据库！"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        if 'conn' in locals():
            conn.close()

if __name__ == "__main__":
    init_db()  # 确保在 app.run() 之前初始化数据库
    app.run(debug=True)